<template>
	<view class="page">
		<c-header bgColor="bg-white">
			<view class="header" slot="header">
				<navigator open-type="navigateBack" :delta="1" hover-class="none" class="t-btn back-btn iconfont f-s48">
					&#xe63b;</navigator>
				<view class="title">
					<view class="pro-name split">{{title}}</view>
					<!-- <text>沟通群</text> -->
				</view>
				<navigator :url="'/package_customer/customer-users/customer-users?gid='+chat_id" hover-class="none"
					class="t-btn menu-btn iconfont f-s48">&#xe8c4;</navigator>
			</view>
		</c-header>
		<view class="body" :style="'height:calc(100% - '+(systemInfo.safeArea.top+44)+'px)'">
			<view class="msg-area" id="J-chat-window" :style="'height:calc(100% - '+footerHeight+'px)'">
				<scroll-view scroll-y="true" @scroll="scroll" :scroll-with-animation="true"
					:scroll-top="chatWindowScrollTop" class="scroll-view-page">
					<view id="J-scroll-body" class="scroll-body">
						<template v-if="loadingState">
							<c-loading :loadingState="loadingState" class="m-t2"></c-loading>
						</template>
						<view v-for="(item,index) in msg" :key="index">
							<view class="chat-wrap">
								<view class="item" :class="item.uid==userInfo.id?'my':'opposite'">
									<view class="avator-name">{{item.name|substringUsername(item.name)}}</view>
									<view class="msg-wrap">
										<view class="user-bar">
											<text class="name">{{item.name}}</text>
											<text class="time">{{item.time}}</text>
										</view>
										<view class="msg">
											<view class="iconfont icon-corrow">&#xeb6d;</view>
											<view class="text">{{item.msg}}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>

			</view>
			<view class="send-msg-area ani">
				<view class="fix-wrap send-area-content" id="J-footer" :style="{'bottom':keyboardHeight+'px'}">
					<view class="inp-bar ani">
						<view class="send-menu-wrap">
							<!-- <view class="btn-wrap">
							<view class="btn menu-btn iconfont f-s54" @click="showMenu">&#xe888;</view>
						</view> -->
							<view class="inp">
								<textarea confirm-type="send" maxlength="-1" :auto-height="textareaParams.autoHeight"
									:fixed="textareaParams.fixed"
									:disable-default-padding="textareaParams.disableDefaultPadding"
									:show-confirm-bar="textareaParams.showConfirm"
									:adjust-position="textareaParams.adjustPosition"
									:cursor-spacing="textareaParams.cursorSpacing" :focus="isFocus" @focus="inpText"
									@linechange="setHeigh" @blur="blurText" @keyboardheightchange="keyboardheightchange"
									v-model="msg_content" />
							</view>
							<!--  	 -->
							<!-- <view class="btn-wrap">
							<view class="btn menu-btn iconfont f-s56" @click="showMenu">&#xe60b;</view>
						</view> -->
							<view v-if="msg_content==''" class="btn-wrap">
								<view class="btn menu-btn iconfont f-s52" @click="showMenu">&#xe635;</view>
							</view>
							<view v-if="msg_content" class="send-btn a-fadeinR">
								<view class="btn" @click="sendMsg">发送</view>
							</view>
						</view>
					</view>
					<view v-if="isMenuShow" class="menu-area a-fadeinB">
						<navigator url="/package_customer/service_doctor/service_doctor" hover-class="none" class="item"
							v-for="(item,index) in 1" :key="index">
							<view class="icon">
								<view class="iconfont f-s48">&#xe7be;</view>
							</view>
							<view class="text">图片</view>
						</navigator>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getSystemInfo
	} from '@/common/promise.js'
	import WebSocket from '@/common/websocket.js'
	import {
		dateFormat
	} from '@/common/util.js'
	export default {
		name: 'demo',
		data() {
			return {
				title: '',
				pro_id: '',
				userInfo: uni.getStorageSync('userInfo'),
				systemInfo: {},
				isMenuShow: false,
				isFocus: false,
				msg_content: '',
				keyboardHeight: 0, // app 键盘高度
				scroll_change: 0,
				chatWindowScrollTop: -1,
				chatWindowHeight: 0,
				footerHeight: 56,
				textareaParams: {
					autoHeight: true,
					showConfirm: false,
					adjustPosition: false,
					disableDefaultPadding: true,
					cursorSpacing: 20,
					fixed: true
				},
				oldScrollTop: 0,
				msg: [],
				chat_users: '',
				chat_id: '',
				page: 1,
				total: 0,
				loadingState: {
					default: true,
					loading: false,
				},
			}
		},
		onShow() {

		},
		async onLoad(params) {
			console.log(params)
			this.pro_id = params.pro_id;
			this.title = params.pro_name;
			this.chat_users = params.chat_users;
			this.chat_id = params.chat_id;
			this.isLogin = await this.$loginState('check');
			if (this.isLogin) {
				if (this.chat_id) {
					this.msg = await this.chatRecord();
					if(this.msg.length>0){
						let msg_read = await this.$api.user_api.chatRead({
							mid: this.msg[this.msg.length - 1].id,
							gid: this.chat_id
						})
						if (msg_read.data.code == 200) {
							this.$store.commit('CHAT_MSG_READ', 1);
						}
						WebSocket.checkSocketState(); // 开启socket聊天
						setTimeout(() => {
							uni.createSelectorQuery().in(this).select("#J-scroll-body").boundingClientRect((
								scroll_data) => {
								uni.createSelectorQuery().in(this).select("#J-chat-window")
									.boundingClientRect((chat_data) => {
										this.$nextTick(function() {
											this.chatWindowScrollTop = scroll_data.height -
												chat_data.height + this.footerHeight;
										});
									}).exec();
							}).exec();
						}, 300)
					}
					
				} else {
					this.chatIndex(); 
				}
			}
		},
		created() {
			// 获取终端系统信息
			this.systemInfo = uni.getStorageSync('systemInfo');
		},
		mounted() {

		},
		onPullDownRefresh() {
			// let _this = this;
			// uni.startPullDownRefresh({
			// 	async success(res) {
			// 		if (_this.total == _this.msg.length) {
			// 			return
			// 		}
			// 		_this.page++;
			// 		_this.loadingState.loading = true;
			// 		let old_msg = await _this.chatRecord();
			// 		_this.msg = old_msg.concat(_this.msg); 
			// 	}
			// });
			// setTimeout(function() {
			// 	uni.stopPullDownRefresh();
			// }, 800);
		},
		filters: {
			substringUsername(val) {
				if (val) return val.substring(val.length - 2);
			},
		},
		methods: {

			async scroll(e) {
				if (e.target.scrollTop == 0) {
					if (this.total == this.msg.length) {
						this.loadingState.loading = false;
						return
					}
					this.page++;
					this.loadingState.loading = true;
					setTimeout(async () => {
						let old_msg = await this.chatRecord();
						this.msg = old_msg.concat(this.msg);
					}, 800)

				}
			},

			// 获取聊天记录
			async chatRecord() {
				let res = await this.$api.user_api.chatRecord({
					gid: this.chat_id,
					page: this.page,
					limit: 15
				})
				if (res.data.code == 200) {
					this.loadingState.default = false;
					this.loadingState.loading = false;
					this.total = res.data.data.count;
					let date = new Date();
					let today = date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) :
						date.getMonth() + 1) + '-' + ((date.getDate()) < 10 ? '0' + (date.getDate()) : date
						.getDate());
					if (res.data.data.list.length > 0) {
						res.data.data.list.forEach(item => {
							item.time = item.time.split(' ')[0] == today ? item.time.split(' ')[1] : item.time;
						})
					}
					return res.data.data.list.reverse();
				}
			},

			// 创建聊天群
			async chatIndex() {
				let _this = this;
				let res = await this.$api.user_api.chatIndex({
					pid: this.pro_id,
					name: this.title,
					users: this.chat_users
				}) 
				if (res.data.code == 200) {
					this.chat_id = res.data.id;
					WebSocket.checkSocketState(); // 登录成功开启socket聊天
					this.msg = await this.chatRecord(); 
					
					if(this.msg.length>0){
						let msg_read = await this.$api.user_api.chatRead({
							mid: this.msg[this.msg.length - 1].id,
							gid: this.chat_id
						})
						if (msg_read.data.code == 200) {
							this.$store.commit('CHAT_MSG_READ', 1);
						} 
						setTimeout(() => {
							uni.createSelectorQuery().in(this).select("#J-scroll-body").boundingClientRect((
								scroll_data) => {
								uni.createSelectorQuery().in(this).select("#J-chat-window")
									.boundingClientRect((chat_data) => {
										this.$nextTick(function() {
											this.chatWindowScrollTop = scroll_data.height -
												chat_data.height + this.footerHeight;
										});
									}).exec();
							}).exec();
						}, 300)	
					}
								 
				}
			},

			// 发送消息
			sendMsg() {
				let msg = `{"type":"msg","gid":"${this.chat_id}","msg":"${this.msg_content}"}`;
				WebSocket.sendSocketMessage(msg);
				this.msg_content = '';
			},

			// 显示底部菜单
			showMenu: function() {
				let _this = this;
				let footerHeight = 0;
				if (this.isMenuShow) {
					this.footerHeight = this.sendBarHeight + 20;
				} else {
					this.footerHeight = this.sendBarHeight + 260;
				}
			},

			// textarea 获取焦点  
			inpText: function() {
				let _this = this;
				// this.isFocus = true;

				// 解决scroll-view  scrolltop 相同不更新的问题  
				let differ_val = (Math.random() / 10).toFixed(3);
				uni.createSelectorQuery().in(this).select("#J-scroll-body").boundingClientRect((scroll_data) => {
					uni.createSelectorQuery().in(this).select("#J-chat-window").boundingClientRect((
						chat_data) => {
						_this.$nextTick(function() {
							_this.chatWindowScrollTop = scroll_data.height - chat_data.height +
								_this.footerHeight + differ_val - 0;
						});
					}).exec();
				}).exec();

			},

			// 离开焦点
			blurText() {
				this.isFocus = false;
			},

			// 键盘高度变化
			keyboardheightchange(e) {
				let _this = this;
				this.keyboardHeight = e.target.height;
				uni.createSelectorQuery().in(this).select("#J-footer").boundingClientRect((data) => {
					this.footerHeight = data.height + e.target.height; // 键盘弹起时，底部高度=底部高度+键盘高度 

					// 解决scroll-view  scrolltop 相同不更新的问题
					let differ_val = (Math.random() / 10).toFixed(3);
					uni.createSelectorQuery().in(this).select("#J-scroll-body").boundingClientRect((
					scroll_data) => {
						uni.createSelectorQuery().in(this).select("#J-chat-window").boundingClientRect((
							chat_data) => {
							_this.$nextTick(function() {
								_this.chatWindowScrollTop = scroll_data.height - chat_data
									.height +
									_this.footerHeight;
							});
						}).exec();
					}).exec();

				}).exec();


			},


			// 设置textarea高度
			setHeigh: function(e) {
				if (e.detail.height < 83) {
					uni.createSelectorQuery().in(this).select("#J-footer").boundingClientRect((data) => {
						this.footerHeight = data.height + this.keyboardHeight - 0;

						// 解决scroll-view  scrolltop 相同不更新的问题
						let differ_val = (Math.random() / 10).toFixed(3);
						uni.createSelectorQuery().in(this).select("#J-scroll-body").boundingClientRect((
							scroll_data) => {
							uni.createSelectorQuery().in(this).select("#J-chat-window")
								.boundingClientRect((
									chat_data) => {
									this.$nextTick(function() {
										this.chatWindowScrollTop = scroll_data.height -
											chat_data.height +
											this.footerHeight;
									});
								}).exec();
						}).exec();
					}).exec();
				}
			},


		},
		computed: {
			new_msg() {
				return this.$store.state.socket_msg_data
			}

		},
		watch: {
			async new_msg(newer, older) {
				console.log(newer)
				if (newer.type == 'msg') {
					if (newer.gid == this.chat_id) {
						let date = new Date();
						let today = date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() +
							1) : date.getMonth() + 1) + '-' + ((date.getDate()) < 10 ? '0' + (date.getDate()) :
							date.getDate());
						newer.time = newer.time.split(' ')[0] == today ? newer.time.split(' ')[1] : newer.time;
						this.msg.push(newer);
						let res = await this.$api.user_api.chatRead({
							mid: newer.mid,
							gid: newer.gid
						})
						if (res.data.code == 200) {
							this.$store.commit('CHAT_MSG_READ', 1);
						}
						setTimeout(() => {
							uni.createSelectorQuery().in(this).select("#J-scroll-body").boundingClientRect((
								scroll_data) => {
								uni.createSelectorQuery().in(this).select("#J-chat-window")
									.boundingClientRect((chat_data) => {
										this.$nextTick(function() {
											this.chatWindowScrollTop = scroll_data.height -
												chat_data.height + this.footerHeight - 0;
										});
									}).exec();
							}).exec();
						}, 300)
					}
				}

			}
		},
		components: {

		}
	}
</script>

<style lang="less" scoped>
	.page,
	.body {
		height: 100%;
		width: 100%;
	}

	.body {
		// display: flex;
		// flex-direction: column;
	}

	.title {
		width: 60%;
		display: flex;
		justify-content: center;

		.pro-name {
			max-width: 80%;
		}

		text {
			flex-shrink: 0;
		}
	}

	.msg-area {
		flex-grow: 2;
		padding-bottom: 20rpx;
	}

	.send-msg-area {
		height: 56px;

		.fix-wrap {
			bottom: 0;
			background: #f1f1f1;
			border-top: 1rpx solid #eee;
		}
	}

	.chat-wrap {
		padding-top: 40rpx;

		.item {
			display: flex;
			align-items: flex-start;
			margin-bottom: 60rpx;

			.avator-name {
				flex-shrink: 0;
				width: 80rpx;
				height: 80rpx;
				line-height: 80rpx;
				margin: 0 30rpx 0;
				background: #09f;
				border-radius: 10rpx;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
			}

			.msg-wrap {
				max-width: 70%;
				position: relative;

				.icon-corrow {
					position: absolute;
					top: 20rpx;
				}

				.user-bar {
					position: absolute;
					z-index: 1;
					width: 400rpx;
					height: 30rpx;
					margin-bottom: 8rpx;
					font-size: 26rpx;
				}

				.msg {
					position: relative;
					top: 40rpx;
					padding: 20rpx;
					border-radius: 10rpx;
					font-size: 30rpx;
				}
			}
		}

		.my {
			flex-direction: row-reverse;

			.user-bar {
				display: flex;
				flex-direction: row-reverse;
				right: 0;

				.time {
					margin-right: 10rpx;
				}
			}

			.msg {
				background: #55ff00;

				.icon-corrow {
					transform: rotate(-90deg);
					right: -22rpx;
					color: #55ff00;
				}
			}
		}

		.opposite {
			.user-bar {
				left: 0;

				.name {
					margin-right: 10rpx;
				}
			}

			.msg {
				background: #fff;

				.icon-corrow {
					transform: rotate(90deg);
					left: -22rpx;
					color: #fff;
				}
			}
		}
	}

	.send-menu-wrap {
		display: flex;
		padding: 0 10rpx;

		.btn {
			flex-shrink: 0;
			width: 38px;
			height: 38px;
			line-height: 38px;
			margin: 8px 0;
			text-align: center;
		}

		.inp {
			flex-grow: 2;
			min-height: 20px;
			margin: 8px 10px;
			max-height: 74px;
			padding: 8px;
			overflow: auto;
			background: #fff;
			border-radius: 12rpx;

			textarea {
				width: 100%;
				height: 100%;
				font-size: 30rpx;
				word-wrap: break-word;
			}
		}

		.send-btn {
			display: flex;

			.btn {
				align-self: flex-end;
				height: 38px;
				line-height: 38px;
				padding: 0 10px;
				background: #09f;
				border-radius: 10rpx;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
			}
		}
	}
</style>
